propsage.namespace("prestige.transaction");

prestige.transaction.addcase = (function($, ui){   
	var selectedType = null;
	var selectedSubtype = null;
        
	function findType(typeName) {
		var data = $.grep(types, function(type, index) {
			return type.typeName == typeName;
		});
        
		return data[0];
	}
    
	function findSubtype(subtypename, subtypes)
	{
		var data =  $.grep(subtypes, function(subtype, index){
			return subtype.subtypeName == subtypename;
		});
        
		return data[0];
	}

	function initComponents() {  
		var $propertyTypeInput = $('#Property_prop_type');
		if ($propertyTypeInput.length == 0) {
			$propertyTypeInput = $('#PropertyCase_pref_prop_type');
		}
        
		if ($propertyTypeInput.val() != '') {
			var inputId = $propertyTypeInput.attr('id');
			var prefix = inputId.substring(0, inputId.indexOf('_prop'));
			selectedType = findType($propertyTypeInput.val());
            
			if (selectedType && selectedType.subtypes != null) {
				$('#' + prefix + '_prop_subtype').parent().show();
                
				// hide empty subtypes and property models
				if ($('#' + prefix + '_prop_subtype').val() != '') {
					selectedSubtype = findSubtype($('#' + prefix + '_prop_subtype').val(), selectedType.subtypes);
            
					if (selectedSubtype.models != null) {
						$('#' + prefix + '_prop_model').parent().show();
					}
				}
			}
		}
	}
    
	function initEventHandlers() {
		for (var i = 0; i < 4; i++) {
			$('#btnSearchPostalcodeContact' + i).PsSearchPostcode({
				'fields': {
					'postcode': '#Contact_' + i + '_postcode',
					'block': '#Contact_' + i + '_block',
					'street': '#Contact_' + i + '_street',
					'building_name': '#Contact_' + i + '_building',
					'district': '#Contact_' + i + '_district',
					'country_code': '#Contact_' + i + '_country_code'
				}
			});
            
//			$('#btnChooseContact' + i).PsChooseContact({                
//				'clearButton': '#btnClearContact' + i,
//				'fields': {
//					'id': '#Contact_' + i + '_id',
//					'type': '#Contact_' + i + '_type',
//					'name': '#Contact_' + i + '_name',
//					'mobile': '#Contact_' + i + '_mobile',
//					'email': '#Contact_' + i + '_email',
//					'birthday': '#Contact_' + i + '_birthday',
//					'company': '#Contact_' + i + '_company',
//					'company_registration_no': '#Contact_' + i + '_company_registration_no',
//					'nric': '#Contact_' + i + '_nric',
//					'nric_type': '#Contact_' + i + '_nric_type',
//					'block': '#Contact_' + i + '_block',
//					'street': '#Contact_' + i + '_street',
//					'floor': '#Contact_' + i + '_floor',
//					'unit': '#Contact_' + i + '_unit',
//					'building': '#Contact_' + i + '_building',
//					'address_1': '#Contact_' + i + '_address_1',
//					'address_2': '#Contact_' + i + '_address_2',
//					'postcode': '#Contact_' + i + '_postcode',
//					'country_code': '#Contact_' + i + '_country_code'
//				},
//				'fieldsToDisable': ['name'],
//				'onContactSelected': function(contact) {
//					var isPerson = contact.type == '0';
//					$(this.clearButton).closest('table').find('.contact-type-person').toggle(isPerson);
//					$(this.clearButton).closest('table').find('.contact-type-organization').toggle(!isPerson);
//				},
//				'clearSelectedContact': function() {
//					$(this.clearButton).closest('table').find('.duplicateAddress').prop('checked', false);
//					$(this.clearButton).closest('table').find('.contact-type-person').show();
//					$(this.clearButton).closest('table').find('.contact-type-organization').hide();
//				}
//				
//			});
			
			$('#Contact_' + i + '_block').change(onContactAddressFieldChange);
			$('#Contact_' + i + '_street').change(onContactAddressFieldChange);
			$('#Contact_' + i + '_floor').change(onContactAddressFieldChange);
			$('#Contact_' + i + '_unit').change(onContactAddressFieldChange);
			$('#Contact_' + i + '_building').change(onContactAddressFieldChange);
			$('#Contact_' + i + '_country_code').change(onContactAddressFieldChange);
			$('#Contact_' + i + '_postcode').change(onContactAddressFieldChange);
            
			$('#duplicateAddress_' + i).change(onDuplicateAddressChange);
		}
        		
		$('#Property_prop_block').keydown(onAddressFieldChange);
		$('#Property_prop_street').keydown(onAddressFieldChange);
		$('#Property_prop_floor').keydown(onAddressFieldChange);
		$('#Property_prop_unit').keydown(onAddressFieldChange);
		$('#Property_prop_project_name').keydown(onAddressFieldChange);
		$('#Property_country_code').change(onAddressFieldChange);
		$('#Property_prop_postcode').keydown(onAddressFieldChange);
        
		$('#btnSearchPostalcode').PsSearchPostcode();
		$('#PropertyCase_type').change(onPropertyCaseTypeChange);
		$('#Property_prop_type, #PropertyCase_pref_prop_type').change(onPropertyTypeSelect);
		$('#Property_prop_subtype, #PropertyCase_pref_prop_subtype').change(onPropertySubtypeSelect);        
		$('#Contact_0_address_1, #Contact_0_address_2, #Contact_1_address_1, #Contact_1_address_2, #Contact_2_address_1, #Contact_2_address_2, #Contact_3_address_1, #Contact_3_address_2, #Property_prop_street, #Property_prop_project_name').change(onAddressChange);
		$('#btnChangeCaseType').click(onButtonChangeCase);
        
		$('#PropertyCase_is_exclusive').change(onIsExclusiveChange);
		
		$('#PropertyCase_valid_period').change(onValidPeriodChange);
		$('#PropertyCase_valid_period_unit').change(onValidPeriodUnitChange);
		$('#PropertyCase_valid_date_start_datepicker').change(onValidDateStartChange);
		$('#PropertyCase_valid_date_end_datepicker').change(onValidDateEndChange);
		
		$('#case-contacts').on('change', '.contact-type input[type=radio]', onContactTypeChange);
		
		// lease expire date auto fill
		$('#PropertyCase_lease_duration').change(onLeaseDurationChange);
		$('#PropertyCase_lease_duration_unit').change(onLeaseDurationUnitChange);
		$('#PropertyCase_lease_start_date_datepicker').change(onLeaseDateStartChange);
		$('#PropertyCase_lease_expiry_date_datepicker').change(onLeaseDateEndChange);
		
		$('.Contact_role_change a.btnChangeContactRole').on('click', onContactRoleChangeClick);
		$('.Contact_role_change a.btnCancelChangeContactRole').on('click', onCancelContactRoleChangeClick);
		$('.Contact_role_change select').on('change', onContactRoleChangeSelectChange);
		
		// initial trigger if propertycase.type != ''
		var $propertyCaseType = $('#PropertyCase_type');
		if($propertyCaseType.val() != '') {
			$propertyCaseType.trigger('change');
		}
	}
	
	function onContactRoleChangeClick(e) {
		$(this).hide();
		$(this).closest('.Contact_role_change').find('select').show();
		$(this).closest('.Contact_role_change').find('a.btnCancelChangeContactRole').show();
	}
	
	function onContactRoleChangeSelectChange(e) {
		$(this).hide();
		$(this).closest('.Contact_role_change').find('a.btnChangeContactRole').show();
		$(this).closest('.Contact_role_change').find('a.btnCancelChangeContactRole').hide();
		
		updateContactRoleHeaders();
	}
	
	function onCancelContactRoleChangeClick(e) {
		$(this).hide();
		$(this).closest('.Contact_role_change').find('select').hide();
		$(this).closest('.Contact_role_change').find('a.btnChangeContactRole').show();		
	}
	
	function updateContactRoleHeaders() {					
		var contactRoles = {};
		$('.Contact_role_header').each(function(index, header) {
			
			var contactRole = $(header).find('select').val();
			
			if (contactRoles[contactRole] == undefined) {
				contactRoles[contactRole] = 1;
			} else {
				contactRoles[contactRole]++;
			}
										
			$('#Contact_'+index+'_role_header .Contact_role_text').text(contactRole + ' #' + contactRoles[contactRole]);
		});
	}
	
	function onContactTypeChange(e) {
		var selectedValue = $(this).val();
		
		var isPerson = selectedValue == 0;
		var $section = $(this).closest('.case-contact-section');
		
		$section.find('.contact-type-organization').toggle(!isPerson);
		$section.find('.contact-type-person').toggle(isPerson);
	}
	
	function onValidPeriodChange() {
		var validPeriod = parseInt($('#PropertyCase_valid_period').val());
		var validPeriodUnit = $('#PropertyCase_valid_period_unit').val();
		
		if (!isNaN(validPeriod)) {
			var m = moment($('#PropertyCase_valid_date_start_datepicker').datepicker('getDate'));
				
			if (m != null) {
				m.add(validPeriodUnit, validPeriod);
				if (validPeriodUnit == 'months') {
					m.subtract('days', 1);
				}
				
				var endDate = m.toDate();
				$('#PropertyCase_valid_date_end_datepicker').datepicker('setDate', endDate);
			}
		}
	}
	
	function onValidPeriodUnitChange() {
		var validPeriod, validPeriodUnit = $('#PropertyCase_valid_period_unit').val();
		
		var m1 = moment($('#PropertyCase_valid_date_start_datepicker').datepicker('getDate'));
		var m2 = moment($('#PropertyCase_valid_date_end_datepicker').datepicker('getDate'));
		
		if (validPeriodUnit == 'days') {
			validPeriod = Math.abs(m2.diff(m1, 'days'));
		} else {
			validPeriod = Math.abs(m2.diff(m1, 'months'));
		}
		
		$('#PropertyCase_valid_period').val(validPeriod);
		
		onValidPeriodChange();
	}
	
	function onValidDateStartChange() {
		onValidPeriodChange();
	}
	
	function onValidDateEndChange() {
		var validPeriod = parseInt($('#PropertyCase_valid_period').val());
		var validPeriodUnit = $('#PropertyCase_valid_period_unit').val();
		
		if (!isNaN(validPeriod)) {
			var m = moment($('#PropertyCase_valid_date_end_datepicker').datepicker('getDate'));
				
			if (m != null) {
				m.subtract(validPeriodUnit, validPeriod);
				if (validPeriodUnit == 'months') {
					m.add('days', 1);
				}
				
				var endDate = m.toDate();
				$('#PropertyCase_valid_date_start_datepicker').datepicker('setDate', endDate);
			}
		}
	}
    
	function onIsExclusiveChange() {
		var is_exclusive = $(this).val();
        
		if (is_exclusive == 0) {
			$('#exclusive_extra').hide();
		} else {
			$('#exclusive_extra').show();
		}
	}
    
	function onButtonChangeCase(event) {
		event.preventDefault();
        
		$('#case-type-select').show();
		$('#PropertyCase_type').val('');
		$('#case-info').hide();
		$('#case-contacts').hide();
		$('#property-address').hide();
		$('.submit-buttons').hide();
	}
    
    
	function onAddressChange() {
		$(this).val(toTitleCase($(this).val())).trigger('keydown');
	}
    
	function toTitleCase(str)
	{
		return str.replace(/\w\S*/g, function(txt){
			return txt.charAt(0).toUpperCase() + txt.substr(1);
		});
	}
    
	function onAddressFieldChange(event) {
		var id = $(this).attr('id');
		var mapFrom = id.replace('Property_prop_', '');
		var $this = $(this);
		
		var mapTo = mapFrom;
		if (mapFrom == 'project_name') {
			mapTo = 'building';
		}
        
		$('.duplicateAddress').each(function() {
			var checked = $(this).is(':checked');
            
			if (checked) {
				var checkbox = $(this);
				setTimeout(function() {
					var checkboxId = checkbox.attr('id');
					var i = checkboxId.replace('duplicateAddress_', '');
					var field = '#Contact_' + i + '_' + mapTo;
                
					$(field).val($this.val());
				},5);
			}
		});
	}
    
	function onContactAddressFieldChange(event) {
		$(this).closest('table').find('input[type=checkbox].duplicateAddress').prop('checked', false);
        
		$(this).closest('table').find('input[type=text], select').removeClass('ps-autofilled');
	}
    
	function onDuplicateAddressChange(event) {
		var checked = $(this).is(':checked');
        
		var i = $(this).attr('id').replace('duplicateAddress_', '');
            
		if(checked){            
			$('#Contact_' + i + '_block').addClass('ps-autofilled').val($('#Property_prop_block').val()).trigger('keydown');
			$('#Contact_' + i + '_street').addClass('ps-autofilled').val($('#Property_prop_street').val()).trigger('keydown');
			$('#Contact_' + i + '_floor').addClass('ps-autofilled').val($('#Property_prop_floor').val()).trigger('keydown');
			$('#Contact_' + i + '_unit').addClass('ps-autofilled').val($('#Property_prop_unit').val()).trigger('keydown');
			$('#Contact_' + i + '_building').addClass('ps-autofilled').val($('#Property_prop_project_name').val()).trigger('keydown');
			$('#Contact_' + i + '_country_code').addClass('ps-autofilled').val($('#Property_country_code').val()).trigger('keydown');
			$('#Contact_' + i + '_postcode').addClass('ps-autofilled').val($('#Property_prop_postcode').val()).trigger('keydown');
		} else {
			$('#Contact_' + i + '_block').removeClass('ps-autofilled').val('').trigger('keydown');
			$('#Contact_' + i + '_street').removeClass('ps-autofilled').val('').trigger('keydown');
			$('#Contact_' + i + '_floor').removeClass('ps-autofilled').val('').trigger('keydown');
			$('#Contact_' + i + '_unit').removeClass('ps-autofilled').val('').trigger('keydown');
			$('#Contact_' + i + '_building').removeClass('ps-autofilled').val('').trigger('keydown');
			$('#Contact_' + i + '_country_code').removeClass('ps-autofilled').val('').trigger('keydown');
			$('#Contact_' + i + '_postcode').removeClass('ps-autofilled').val('').trigger('keydown');
		}
	}
    
	function parseAddress(address) {
		var matches, block, floor, unit, street, building;
		var tmp = address, tmp2 = address;
        
		var blockRegex = /Blk|Block (\w+)/gi;
		var floorUnitRegex = /#(\w+)\-(\w+)/g;
		var streetRegex = /(\d+\w{0,1})*([\w**\s*]+\d*)/i
        
		var split2;
        
		if (tmp.indexOf(',')) {
			split2 = $.trim(tmp).split(',');
		} else {
			split2 = '';
		}
        
		matches = blockRegex.exec(tmp);
		if (matches) {
			block = matches[1];
			tmp = tmp.replace(blockRegex, '&&&');
			tmp2 = tmp2.replace(blockRegex, '');
		}
        
		matches = floorUnitRegex.exec(tmp);        
		if (matches) {
			floor = matches[1];
			unit = matches[2];
			tmp = tmp.replace(floorUnitRegex, '&&&');
			tmp2 = tmp2.replace(floorUnitRegex, '');
		}
        
		var split1= $.trim(tmp).split('&&&');
		if (split1 != null) {
			var split = split1.concat(split2);
		} else {
			split = split2;
		}
        
		$.each(split, function(i, v) {
			v = $.trim(v);
			matches = streetRegex.exec(v);
			if (matches) {
				if (block == null && matches[1] != null)  {
					block = $.trim(matches[1]);
					street = $.trim(matches[2]);
                    
					tmp2 = tmp2.replace(block, '');
					tmp2 = tmp2.replace(street, '');
				}
			}
		});
        
		tmp2 = $.trim(tmp2.replace(/\,/gi, ''));
		if (tmp2 != '') {
			building = tmp2;
		}
        
		tmp = $.trim(tmp).replace(/&&&/gi, '');
		tmp = $.trim(tmp).replace(/\,/gi, '');
        
		tmp = $.trim(tmp).replace(streetRegex, '');
                
		return {
			'block': block,
			'street': street,
			'floor': floor,
			'unit': unit,
			'building': building
		};
	}
    
	function onPropertySubtypeSelect(event) {
		event.preventDefault();
        
		var id = $(this).attr('id');
		var prefix = id.substring(0, id.indexOf('_prop'));
		var subtypeName = $(this).val();        
		selectedSubtype = findSubtype(subtypeName, selectedType.subtypes);
                
		if (selectedSubtype != null && selectedSubtype.models != null && selectedSubtype.models.length > 0) {
			var modelOptions = '<option value=""></option>';
        
			$.each(selectedSubtype.models, function(i, model) {
				modelOptions += '<option value="' + model + '">' + model + '</option>';
			});
        
			$('#' + prefix + '_model_block').show();
			$('#' + prefix + '_prop_model').html(modelOptions);
			$('#' + prefix + '_prop_model').siblings('label').show();
		} else {
			$('#' + prefix + '_prop_model').val('').parent().hide();
			$('#' + prefix + '_prop_model').siblings('label').hide();
		}
        
	}

	function onPropertyTypeSelect(event){
		event.preventDefault();
        
		var id = $(this).attr('id');
		var prefix = id.substring(0, id.indexOf('_prop'));
		var propType = $(this).val();
		selectedType = findType(propType);
        
		if (propType == '') {
			$('#' + prefix + '_prop_subtype').val('').parent().hide();
		} else {
			var subtypeOptions = '<option value=""></option>';
            
			if (selectedType.subtypes != null) {
				$.each(selectedType.subtypes, function(i, subtype) {
					subtypeOptions += '<option value="' + subtype.subtypeName + '">' + subtype.subtypeName + '</option>';
				});
			}
            
			$('#' + prefix + '_subtype_block').show();
			$('#' + prefix + '_prop_subtype').html(subtypeOptions);
		}
        
		$('#' + prefix + '_prop_model').val('').parent().hide();
	}
    
	function onPropertyCaseTypeChange(event) {
		var caseType = $(this).val();
        
		if (caseType != '') {
			$('#case-type-select').hide();
			$('#case-info').show();
			$('#case-contacts').show();
			$('#property-address').show();
        
			$('#case-type').text(caseType);
        
			
			if (caseType == 'Lease by Landlord' || caseType == 'Lease by Tenant') {
				$('.rental').show();
			} else {
				$('.rental').hide();
			}
        
			$('.submit-buttons').show();
        
			var clientType = null;
			var clientRole = null;
			var contactRoles = {};
			
			var agencySettings = clientTypesAgencySetting[caseType];			
			
			if(agencySettings) {
				$.each(agencySettings, function(contactNum, settings) {
					if(settings['role']) {
						clientRole = settings['role'];
					} else {
						clientRole = clientTypes[caseType];
					}
					var index = contactNum-1;
					
					if (contactRoles[clientRole] == undefined) {
						contactRoles[clientRole] = 1;
					} else {
						contactRoles[clientRole]++;
					}
										
					$('#Contact_'+index+'_role').val(clientRole);
					$('#Contact_'+index+'_role_header .Contact_role_text').text(clientRole + ' #' + contactRoles[clientRole]);
					
					
					if(settings['type']) {
						clientType = settings['type'];
					} else {
						clientType = 0;
					}
					$('#Contact_'+index+'_type'+'_'+(clientType)).attr('checked', true);
					$('#Contact_'+index+'_type'+'_'+(clientType)).trigger('change');
				});
			} else {
				clientRole = clientTypes[caseType];
				$('#Contact_0_role').val(clientRole);
				$('#Contact_1_role').val(clientRole);
			}
        
			$('.tx-type').text(caseType);
		}
	}
    
	function onLeaseDurationChange() {
		var leaseDuration = parseInt($('#PropertyCase_lease_duration').val());
		var leaseDurationUnit = $('#PropertyCase_lease_duration_unit').val();
		
		if (!isNaN(leaseDuration)) {
			var m = moment($('#PropertyCase_lease_start_date_datepicker').datepicker('getDate'));
			if (m != null) {
				m.add(leaseDurationUnit, leaseDuration);
				if (leaseDurationUnit == 'months') {
					m.subtract('days', 1);
				}
				if (leaseDurationUnit == 'years') {
					m.subtract('days', 1);
				}
				
				var endDate = m.toDate();
				$('#PropertyCase_lease_expiry_date_datepicker').datepicker('setDate', endDate);
			}
		}
	}
	
	function onLeaseDurationUnitChange() {
		var leaseDuration, leaseDurationUnit = $('#PropertyCase_lease_duration_unit').val();
		
		var m1 = moment($('#PropertyCase_lease_start_date_datepicker').datepicker('getDate'));
		var m2 = moment($('#PropertyCase_lease_expiry_date_datepicker').datepicker('getDate'));
		
		if (leaseDurationUnit == 'years') {
			leaseDuration = Math.abs(m2.diff(m1, 'years'));
		} else {
			leaseDuration = Math.abs(m2.diff(m1, 'months'));
		}
		
		$('#PropertyCase_lease_duration').val(leaseDuration);
		
		onLeaseDurationChange();
	}
	
	function onLeaseDateStartChange() {
		onLeaseDurationChange();
	}
	
	function onLeaseDateEndChange() {
		var leaseDuration = parseInt($('#PropertyCase_lease_duration').val());
		var leaseDurationUnit = $('#PropertyCase_lease_duration_unit').val();
		
		if (!isNaN(leaseDuration)) {
			var m = moment($('#PropertyCase_lease_expiry_date_datepicker').datepicker('getDate'));
				
			if (m != null) {
				m.subtract(leaseDurationUnit, leaseDuration);
				if (leaseDurationUnit == 'months') {
					m.add('days', 1);
				}
				if (leaseDurationUnit == 'years') {
					m.add('days', 1);
				}
				
				var endDate = m.toDate();
				$('#PropertyCase_lease_start_date_datepicker').datepicker('setDate', endDate);
			}
		}
	}
	
    
	$(document).ready(function() {
		initComponents();
		initEventHandlers();
	});
})(jQuery, prestige.ui);